package com.maisha.filter;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.maisha.bean.Auditor;
import com.maisha.utils.CMSConstant;
import com.maisha.utils.CookieUtils;

public class CMSPowerFilter implements Filter{

	private ServletContext application; 
	
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest requset, ServletResponse response,
			FilterChain chan) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) requset;
		HttpServletResponse res = (HttpServletResponse) response; 
		//获得 application currentHashMap 判断是否需要 重新登录
		//从session  中获得 用户登录信息
		Auditor auditor = (Auditor) req.getSession().getAttribute(CMSConstant.SESSION_AUDITOR_KEY);
		if(CMSConstant.NOT_CHECK_FILTER_URL.contains(getServletPath(req.getServletPath()))){
			if(CMSConstant.NOT_CHECK_SESSION_URL.contains(getServletPath(req.getServletPath()))){ //检测 session 是否过期
				chan.doFilter(requset, response);
			}else{
				if(auditor!=null){
					chan.doFilter(requset, response);
				}else{
					res.sendRedirect("loginIn.htm");
				}
			}
		}else{
			ConcurrentHashMap<String, String> auditMap =  (ConcurrentHashMap<String, String>) application.getAttribute(CMSConstant.IS_REFRESH_NOW_KEY);
			if(auditor==null){
				res.sendRedirect("loginIn.htm");
			}else{
				if(auditMap!=null && !auditMap.isEmpty()){
					if(auditMap.get(auditor.getId())!=null){ // 删除session,cookie,强制 用户跳转到 input 页面
						synchronized (this) { //同步 保证 application 中的map 不会脏读
							auditMap = (ConcurrentHashMap<String, String>) application.getAttribute(CMSConstant.IS_REFRESH_NOW_KEY);
							CookieUtils.deleteCookie(res, CMSConstant.COOKIE_AUDITOR_KEY);
							req.getSession().setAttribute(CMSConstant.SESSION_AUDITOR_KEY, null);
							auditMap.remove(auditor.getId());
							application.setAttribute(CMSConstant.IS_REFRESH_NOW_KEY,auditMap);
							res.sendRedirect("loginIn.htm");
						}
					}else{
						chan.doFilter(requset, response);
					}
				}else{
					chan.doFilter(requset, response);
				}
			}
		}
	}
	
	/** 截取 uri 获得 方法的路径
	 * @param path
	 * @return
	 */
	private String getServletPath(String path){
		if(StringUtils.isNotBlank(path)){
			path = path.substring(path.lastIndexOf("/")+1);
		}
		return path;
	}
	
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		application = filterConfig.getServletContext();  
	}

}
